package com.my.ads.lib.live.account;

import android.Manifest;
import android.accounts.Account;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;

import com.example.myadlib.R;

import static android.content.Context.ACCOUNT_SERVICE;

/**
 * Created by xuanyang on 2018/3/9.
 */

public class ManagerAccount {

    public static void addAccount(Context ctx) {
        //添加账号
        String ACCOUNT_TYPE = ctx.getString(R.string.account_type);
        String CONTENT_AUTHORITY = ctx.getString(R.string.account_provider_authority);

        try{

            PackageManager pm = ctx.getPackageManager();
            if (PackageManager.PERMISSION_GRANTED !=
                    pm.checkPermission(Manifest.permission.GET_ACCOUNTS, ctx.getPackageName())){
                return;
            }
            android.accounts.AccountManager accountManager = (android.accounts.AccountManager) ctx.getSystemService(ACCOUNT_SERVICE);
            Account account = null;
            if (accountManager.addAccountExplicitly(account, null, null)) {
                // 开启同步，设置同步周期  30秒
                ContentResolver.setIsSyncable(account, CONTENT_AUTHORITY, 1);
                ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, true);
                ContentResolver.addPeriodicSync(account, CONTENT_AUTHORITY, Bundle.EMPTY, 30);
            }
            Account[] accountsByType = accountManager.getAccountsByType(ACCOUNT_TYPE);
            if (accountsByType.length > 0) {
                account = accountsByType[0];
            } else {
                account = new Account(ctx.getString(R.string.app_name), ACCOUNT_TYPE);
            }

            if (accountManager.addAccountExplicitly(account, null, null)) {
                // 开启同步，设置同步周期  30秒
                ContentResolver.setIsSyncable(account, CONTENT_AUTHORITY, 1);
                ContentResolver.setSyncAutomatically(account, CONTENT_AUTHORITY, true);
                ContentResolver.addPeriodicSync(account, CONTENT_AUTHORITY, Bundle.EMPTY, 30);
            }

        }catch (Exception e){
            e.printStackTrace();
        }



    }
}
